/*
 * Copyright 2008-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.faxsun.controller.account;

import org.broadleafcommerce.common.exception.ServiceException;
import org.broadleafcommerce.core.web.controller.account.BroadleafManageCustomerAddressesController;
import org.broadleafcommerce.core.web.controller.account.CustomerAddressForm;
import org.broadleafcommerce.core.web.controller.account.validator.CustomerAddressValidator;
import org.broadleafcommerce.profile.core.domain.Country;
import org.broadleafcommerce.profile.core.domain.Customer;
import org.broadleafcommerce.profile.core.domain.CustomerAddress;
import org.broadleafcommerce.profile.core.domain.State;
import org.broadleafcommerce.profile.core.service.AddressService;
import org.broadleafcommerce.profile.core.service.CountryService;
import org.broadleafcommerce.profile.core.service.CustomerAddressService;
import org.broadleafcommerce.profile.core.service.StateService;
import org.broadleafcommerce.profile.web.core.CustomerState;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.faxsun.profile.core.domain.FSAddress;
import com.faxsun.profile.core.domain.FSReceiver;
import com.faxsun.profile.core.service.FSReceiverService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;

@Controller
@RequestMapping("/account/addresses")
public class ManageCustomerAddressesController extends BroadleafManageCustomerAddressesController {

	@Resource(name = "blCustomerAddressService")
	private CustomerAddressService customerAddressService;
	@Resource(name = "blAddressService")
	private AddressService addressService;
	@Resource(name = "blCountryService")
	private CountryService countryService;
	@Resource(name = "blCustomerAddressValidator")
	private CustomerAddressValidator customerAddressValidator;
	@Resource(name = "blStateService")
	private StateService stateService;
	@Resource(name = "fsReceiverService")
	protected FSReceiverService fsReceiverService;

	protected String addressUpdatedMessage = "已更新收货地址";
	protected String addressAddedMessage = "成功添加收货地址";
	protected String addressRemovedMessage = "成功删除收货地址";
	protected String addressRemovedErrorMessage = "无法删除当前购物车收货地址，请修改购物车地址后重试";

	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		super.initBinder(request, binder);
	}

	@ModelAttribute("states")
	protected List<State> populateStates() {
		return super.populateStates();
	}

	@ModelAttribute("countries")
	protected List<Country> populateCountries() {
		return super.populateCountries();
	}

	@ModelAttribute("customerAddresses")
	protected List<CustomerAddress> populateCustomerAddresses() {
		return super.populateCustomerAddresses();
	}

	@RequestMapping(method = RequestMethod.GET)
	public String viewCustomerAddresses(HttpServletRequest request, Model model) {
		// return super.viewCustomerAddresses(request, model);
		model.addAttribute("customerAddressForm", new FSCustomerAddressForm());
		return getCustomerAddressesView();
	}

	@RequestMapping(method = RequestMethod.POST)
	public String addCustomerAddress(HttpServletRequest request, Model model,
			@ModelAttribute("customerAddressForm") FSCustomerAddressForm form, BindingResult result,
			RedirectAttributes redirectAttributes) throws ServiceException {

		setCustomer(form);
		return super.addCustomerAddress(request, model, form, result, redirectAttributes);
	}

	@RequestMapping(value = "/{customerAddressId}", method = RequestMethod.GET)
	public String viewCustomerAddress(HttpServletRequest request, Model model,
			@PathVariable("customerAddressId") Long customerAddressId) {
		// return super.viewCustomerAddress(request, model, customerAddressId);
		CustomerAddress customerAddress = customerAddressService.readCustomerAddressById(customerAddressId);
		if (customerAddress == null) {
			throw new IllegalArgumentException(
					"Customer Address not found with the specified customerAddressId");
		}
		CustomerAddressForm form = new FSCustomerAddressForm();
		form.setAddress(customerAddress.getAddress());
		form.setAddressName(customerAddress.getAddressName());
		form.setCustomerAddressId(customerAddress.getId());
		model.addAttribute("customerAddressForm", form);
		return getCustomerAddressesView();

	}

	@RequestMapping(value = "/{customerAddressId}", method = RequestMethod.POST)
	public String updateCustomerAddress(HttpServletRequest request, Model model,
			@PathVariable("customerAddressId") Long customerAddressId,
			@ModelAttribute("customerAddressForm") FSCustomerAddressForm form, BindingResult result,
			RedirectAttributes redirectAttributes) throws ServiceException {
		setCustomer(form);
		return super.updateCustomerAddress(request, model, customerAddressId, form, result,
				redirectAttributes);
	}

	@RequestMapping(value = "/{customerAddressId}", method = RequestMethod.POST, params = "removeAddress")
	public String removeCustomerAddress(HttpServletRequest request, Model model,
			@PathVariable("customerAddressId") Long customerAddressId, RedirectAttributes redirectAttributes) {
		return super.removeCustomerAddress(request, model, customerAddressId, redirectAttributes);
	}

	private void setCustomer(FSCustomerAddressForm form) {
		FSAddress address = (FSAddress) form.getAddress();
		Customer customer = CustomerState.getCustomer();

		FSReceiver receiver = address.getReceiver();

		if (receiver != null) {
			if (receiver.getIdCard() == null) {
				receiver.setIdCard("");
			}
		}

		// 此处仅设置客户名称，身份证如已输入，则界面上已有身份证信息
		String name = address.getFullName();
		receiver.setName(name);
		receiver.setCustomer(customer);
		// 复用数据库中已有的身份证信息
		FSReceiver receiverInDB = fsReceiverService.readByEntity(receiver);
		if (receiverInDB != null) {
			address.setReceiver(receiverInDB);
		}

		address.getReceiver().setCustomer(customer);
		form.setAddress(address);
	}

	@Override
	public String getAddressUpdatedMessage() {
		return addressUpdatedMessage;
	}

	@Override
	public String getAddressAddedMessage() {
		return addressAddedMessage;
	}

	@Override
	public String getAddressRemovedMessage() {
		return addressRemovedMessage;
	}

	@Override
	public String getAddressRemovedErrorMessage() {
		return addressRemovedErrorMessage;
	}

}